package com.drcoffee.drcoffeemall.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

public class BodyToMapUtil {
    public static Map<String, Object> convertJsonToMap(String json) {
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 使用Jackson库将JSON字符串解析为Map
            Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常
            return Collections.emptyMap(); // 或者返回null，取决于你的需求
        }
    }

    public static void main(String[] args) {
        String jsonRequestBody = "{\"key1\": \"value1\", \"key2\": \"value2\"}";

        Map<String, Object> requestBodyMap = convertJsonToMap(jsonRequestBody);

        // 使用转换后的Map对象
        for (Map.Entry<String, Object> entry : requestBodyMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
